package com.cardbaobao.cardbabyclient.ui.activity;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.expand.ScaleCircleNavigator;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.DensityUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.widget.TitleBar;

import net.lucode.hackware.magicindicator.MagicIndicator;
import java.util.ArrayList;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by Jiangzx on 11:24.
 * 社保查询结果
 */
public class SocialSecurityResultActivity extends BaseActivity {
    @BindView(R.id.title_bar)
    TitleBar titleBar;

    @BindView(R.id.view_pager)
    ViewPager viewPager;

    @BindView(R.id.tv_pager_current)
    TextView tvPagerCurrent;

    @BindView(R.id.magic_indicator)
    MagicIndicator indicator;

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        mCurrentPageId= Self.Page.app_social_security_inquiry_success_page;

        initIntent();
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleBar.setRightBtClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SelfUtils.buriedClickData(Self.Action.app_click_social_security_switch_account,
                        Self.Action.app_click_social_security_switch_account_des,
                        mEnterPageTime,
                        mCurrentPageId,mPrePageId);
                mIntent.setClass(mContext,InquiriesActivity.class);
                mIntent.putExtra(InquiriesActivity.CHANNEL_TYPE_S,
                        InquiriesActivity.CHANNEL_SHE_BAO);
                startActivity(mIntent);
                finish();
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_social_security_result;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(pagerData==null){
            loadSocialSecurityRecord();
        }
    }

    private ArrayList<ListView> views;
    private ArrayList<ArrayList<DataInListView>> pagerData;

    private class ViewPagerAdapter extends PagerAdapter{
        @Override
        public int getCount() {
            return views==null?0:views.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view==object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ListView listView=views.get(position);
            container.addView(listView);
            return listView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ListView listView=views.get(position);
            container.removeView(listView);
        }
    }

    private class SocialSecurityAdapter extends BaseAdapter{
        private int radian;
        private int contentLeftPadding;
        private GradientDrawable topBgDrawable;
        private GradientDrawable bottomBgDrawable;
        private Drawable bgNormalDrawable;
        private ArrayList<DataInListView> data;
        SocialSecurityAdapter(ArrayList<DataInListView> data){
            this.data=data;
            this.radian=DensityUtil.dp2px(6);
            this.contentLeftPadding=DensityUtil.dp2px(10);
            this.topBgDrawable=new GradientDrawable(GradientDrawable.Orientation.TL_BR,new int[]{0xffffffff,0xffffffff});
            this.topBgDrawable.setCornerRadii(new float[]{radian,radian,radian,radian,0,0,0,0});
            this.bottomBgDrawable=new GradientDrawable(GradientDrawable.Orientation.TL_BR,new int[]{0xffffffff,0xffffffff});
            this.bottomBgDrawable.setCornerRadii(new float[]{0,0,0,0,radian,radian,radian,radian});
            this.bgNormalDrawable=new ColorDrawable(0xffffffff);
        }
        private static final int ITEM_TYPE_HEADER=1;
        private static final int ITEM_TYPE_CONTENT_TOP=2;
        private static final int ITEM_TYPE_CONTENT_NORMAL=3;
        private static final int ITEM_TYPE_CONTENT_BOTTOM=4;
        private static final int ITEM_TYPE_DIVIDER=5;
        /**
         * Attention!!!
         * VIEW_TYPE_COUNT需大于实际item种类，否则会概率性出现闪退
         * 异常为数组越界异常
         * android.widget.AbsListView$RecycleBin.addScrapView
         */
        private static final int ITEM_TYPE_COUNT=
                ITEM_TYPE_HEADER+ITEM_TYPE_CONTENT_TOP+ITEM_TYPE_CONTENT_NORMAL+
                        ITEM_TYPE_CONTENT_BOTTOM+ITEM_TYPE_DIVIDER;
        @Override
        public int getCount() {
            return data==null?0:data.size();
        }

        @Override
        public Object getItem(int position) {
            return data==null?null:data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            DataInListView item=data.get(position);
            int type=getItemViewType(position);
            if(convertView==null){
                if(type==ITEM_TYPE_HEADER){
                    TextView tv=new TextView(mContext);
                    AbsListView.LayoutParams params=
                            new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
                                    DensityUtil.dp2px(50));
                    tv.setLayoutParams(params);
                    tv.setGravity(Gravity.CENTER_VERTICAL);
                    tv.setText(item.text);
                    tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,16.0f);
                    tv.setTextColor(0xffff9e27);
                    convertView=tv;
                }else if(type==ITEM_TYPE_DIVIDER){
                    View view=new View(mContext);
                    AbsListView.LayoutParams params=
                            new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,2);
                    view.setLayoutParams(params);
                    view.setBackgroundColor(Constant.DIVIDER_COLOR);
                    convertView=view;
                }else{
                    TextView tv=new TextView(mContext);
                    AbsListView.LayoutParams params=
                            new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
                                    DensityUtil.dp2px(mContext,45));
                    tv.setLayoutParams(params);
                    tv.setGravity(Gravity.CENTER_VERTICAL);
                    tv.setText(item.text);
                    tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,15.0f);
                    tv.setTextColor(0xff666666);
                    switch (type){
                        case ITEM_TYPE_CONTENT_TOP:
                            if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN){
                                tv.setBackground(topBgDrawable);
                            }else{
                                tv.setBackgroundDrawable(topBgDrawable);
                            }
                            tv.setPadding(contentLeftPadding,radian,0,0);
                            break;
                        case ITEM_TYPE_CONTENT_BOTTOM:
                            tv.setPadding(contentLeftPadding,0,0,radian);
                            if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN){
                                tv.setBackground(bottomBgDrawable);
                            }else{
                                tv.setBackgroundDrawable(bottomBgDrawable);
                            }
                            break;
                        default:
                            if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN){
                                tv.setBackground(bgNormalDrawable);
                            }else{
                                tv.setBackgroundDrawable(bgNormalDrawable);
                            }
                            tv.setPadding(contentLeftPadding,0,0,0);
                            break;
                    }
                    convertView=tv;
                }
            }
            if(type!=ITEM_TYPE_DIVIDER){
                if(convertView instanceof TextView){
                    ((TextView)convertView).setText(item.text);
                }
            }
            return convertView;
        }

        @Override
        public int getViewTypeCount() {
            return ITEM_TYPE_COUNT;
        }

        @Override
        public int getItemViewType(int position) {
            return data.get(position).type;
        }
    }

    private class Data{
        int person;
        int company;
        String month;
        Data(int person,int company,String month){
            this.person=person;
            this.company=company;
            this.month=month;
        }
    }

    private class DataInListView{
        int type;
        String text;
        String month;
        DataInListView(int type,String text,String month){
            this.type=type;
            this.text=text;
            this.month=month;
        }
    }

    private void handleUi(){
        views=new ArrayList<>();
        for(int i=0,size=pagerData.size();i<size;i++){
            ArrayList<DataInListView> data = pagerData.get(i);
            ListView listView=new ListView(mContext);
            listView.setLayoutParams(
                    new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT));
            listView.setDivider(new ColorDrawable(0));
            listView.setAdapter(new SocialSecurityAdapter(data));
            listView.setVerticalScrollBarEnabled(false);
            views.add(listView);
        }
        viewPager.setAdapter(new ViewPagerAdapter());
        ScaleCircleNavigator scaleCircleNavigator=new ScaleCircleNavigator(mContext);
        scaleCircleNavigator.setCircleCount(views.size());
        scaleCircleNavigator.setNormalCircleColor(0xffafafaf);
        scaleCircleNavigator.setSelectedCircleColor(0xffff9e27);
        scaleCircleNavigator.setMinRadius(DensityUtil.dp2px(mContext,6.0f));
        scaleCircleNavigator.setMaxRadius(DensityUtil.dp2px(mContext,7.5f));
        scaleCircleNavigator.setCircleSpacing(DensityUtil.dp2px(mContext,13.0f));
        scaleCircleNavigator.setCircleClickListener(new ScaleCircleNavigator.OnCircleClickListener() {
            @Override
            public void onClick(int index) {
                viewPager.setCurrentItem(index);
            }
        });
        indicator.setNavigator(scaleCircleNavigator);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                indicator.onPageScrolled(position,positionOffset,positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                indicator.onPageSelected(position);
                tvPagerCurrent.setText("缴费所属期："+pagerData.get(position).get(0).month);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                indicator.onPageScrollStateChanged(state);
            }
        });
        tvPagerCurrent.setText("缴费所属期："+pagerData.get(0).get(0).month);
    }

    //查询社保缴费记录
    private void loadSocialSecurityRecord(){
        showProgressDialog(false);
        Observable<String> observable= Api.querySocialSecurityResult(mApplication.getUser().getID());
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_data_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject json= JSON.parseObject(s);
                //accidentResult 工伤保险
                JSONArray accidentResult=json.getJSONArray("accidentResult");
                //endowmentResult 养老保险
                JSONArray endowmentResult=json.getJSONArray("endowmentResult");
                //maternityResult 生育保险
                JSONArray maternityResult=json.getJSONArray("maternityResult");
                //medicalResult 医疗保险
                JSONArray medicalResult=json.getJSONArray("medicalResult");
                //unemploymentResult 失业保险
                JSONArray unemploymentResult=json.getJSONArray("unemploymentResult");
                ArrayList<ArrayList<Data>>source=new ArrayList<>();
                try{
                    JSONObject object;
                    String month;
                    ArrayList<Data> temp;
                    for(int i=0;i<6;i++){
                        object=accidentResult.getJSONObject(i);
                        month=object.getString("month");
                        temp=new ArrayList<>();
                        temp.add(new Data(
                                object.getIntValue("monthly_personal_income"),
                                object.getIntValue("monthly_company_income"),
                                month));
                        object=endowmentResult.getJSONObject(i);
                        temp.add(new Data(
                                object.getIntValue("monthly_personal_income"),
                                object.getIntValue("monthly_company_income"),
                                month));
                        object=maternityResult.getJSONObject(i);
                        temp.add(new Data(
                                object.getIntValue("monthly_personal_income"),
                                object.getIntValue("monthly_company_income"),
                                month));
                        object=medicalResult.getJSONObject(i);
                        temp.add(new Data(
                                object.getIntValue("monthly_personal_income"),
                                object.getIntValue("monthly_company_income"),
                                month));
                        object=unemploymentResult.getJSONObject(i);
                        temp.add(new Data(
                                object.getIntValue("monthly_personal_income"),
                                object.getIntValue("monthly_company_income"),
                                month));
                        source.add(temp);
                    }

                    pagerData =new ArrayList<>();
                    ArrayList<DataInListView> listData;
                    for(int i=0,size=source.size();i<size;i++){
                        ArrayList<Data> data =source.get(i);
                        int company=0;
                        int personal=0;
                        for(Data d:data){
                            company+=d.company;
                            personal+=d.person;
                        }
                        //去除全是0的項
                        if(company>0||personal>0){
                            listData=new ArrayList<>();
                            String monthInList=data.get(0).month;
                            int calculate=company;
                            //能整除，不显示小数点
                            if(calculate%100==0){
                                listData.add(
                                        new DataInListView(SocialSecurityAdapter.ITEM_TYPE_HEADER,
                                                "统筹总额："+calculate/100+"(单位：元)",
                                                monthInList));
                            }else{
                                listData.add(
                                        new DataInListView(SocialSecurityAdapter.ITEM_TYPE_HEADER,
                                                "统筹总额："+calculate/100.0f+"(单位：元)",
                                                monthInList));
                            }
                            calculate=data.get(4).company;
                            if(calculate%100==0){
                                listData.add(
                                        new DataInListView(SocialSecurityAdapter.ITEM_TYPE_CONTENT_TOP,
                                                "失业保险(统筹)："+calculate/100,
                                                monthInList));
                            }else{
                                listData.add(
                                        new DataInListView(SocialSecurityAdapter.ITEM_TYPE_CONTENT_TOP,
                                                "失业保险(统筹)："+calculate/100.0f,
                                                monthInList));
                            }
                            listData.add(new DataInListView(SocialSecurityAdapter.ITEM_TYPE_DIVIDER,"",""));
                            calculate=data.get(0).company;
                            if(calculate%100==0){
                                listData.add(
                                        new DataInListView(SocialSecurityAdapter.ITEM_TYPE_CONTENT_NORMAL,
                                                "工伤保险(统筹)："+calculate/100,
                                                monthInList));
                            }else{
                                listData.add(
                                        new DataInListView(SocialSecurityAdapter.ITEM_TYPE_CONTENT_NORMAL,
                                                "工伤保险(统筹)："+calculate/100.0f,
                                                monthInList));
                            }
                            listData.add(new DataInListView(SocialSecurityAdapter.ITEM_TYPE_DIVIDER,"",""));
                            calculate=data.get(1).company;
                            if(calculate%100==0){
                                listData.add(
                                        new DataInListView(SocialSecurityAdapter.ITEM_TYPE_CONTENT_NORMAL,
                                                "养老保险(统筹)："+calculate/100,
                                                monthInList));
                            }else{
                                listData.add(
                                        new DataInListView(SocialSecurityAdapter.ITEM_TYPE_CONTENT_NORMAL,
                                                "养老保险(统筹)："+calculate/100.0f,
                                                monthInList));
                            }
                            listData.add(new DataInListView(SocialSecurityAdapter.ITEM_TYPE_DIVIDER,"",""));
                            calculate=data.get(3).company;
                            if(calculate%100==0){
                                listData.add(
                                        new DataInListView(SocialSecurityAdapter.ITEM_TYPE_CONTENT_NORMAL,
                                                "医疗保险(统筹)："+calculate/100,
                                                monthInList));
                            }else{
                                listData.add(
                                        new DataInListView(SocialSecurityAdapter.ITEM_TYPE_CONTENT_NORMAL,
                                                "医疗保险(统筹)："+calculate/100.0f,
                                                monthInList));
                            }
                            listData.add(new DataInListView(SocialSecurityAdapter.ITEM_TYPE_DIVIDER,"",""));
                            calculate=data.get(2).company;
                            if(calculate%100==0){
                                listData.add(
                                        new DataInListView(SocialSecurityAdapter.ITEM_TYPE_CONTENT_BOTTOM,
                                                "生育保险(统筹)："+calculate/100,
                                                monthInList));
                            }else{
                                listData.add(
                                        new DataInListView(SocialSecurityAdapter.ITEM_TYPE_CONTENT_BOTTOM,
                                                "生育保险(统筹)："+calculate/100.0f,
                                                monthInList));
                            }
                            calculate=personal;
                            if(calculate%100==0){
                                listData.add(
                                        new DataInListView(SocialSecurityAdapter.ITEM_TYPE_HEADER,
                                                "个人总额："+calculate/100+"(单位：元)",
                                                monthInList));
                            }else{
                                listData.add(
                                        new DataInListView(SocialSecurityAdapter.ITEM_TYPE_HEADER,
                                                "个人总额："+calculate/100.0f+"(单位：元)",
                                                monthInList));
                            }
                            calculate=data.get(3).person;
                            if(calculate%100==0){
                                listData.add(
                                        new DataInListView(SocialSecurityAdapter.ITEM_TYPE_CONTENT_TOP,
                                                "医疗保险(个人)："+calculate/100,
                                                monthInList));
                            }else{
                                listData.add(
                                        new DataInListView(SocialSecurityAdapter.ITEM_TYPE_CONTENT_TOP,
                                                "医疗保险(个人)："+calculate/100.0f,
                                                monthInList));
                            }
                            listData.add(new DataInListView(SocialSecurityAdapter.ITEM_TYPE_DIVIDER,"",""));
                            calculate=data.get(1).person;
                            if(calculate%100==0){
                                listData.add(
                                        new DataInListView(SocialSecurityAdapter.ITEM_TYPE_CONTENT_NORMAL,
                                                "养老保险(个人)："+calculate/100,
                                                monthInList));
                            }else{
                                listData.add(
                                        new DataInListView(SocialSecurityAdapter.ITEM_TYPE_CONTENT_NORMAL,
                                                "养老保险(个人)："+calculate/100.0f,
                                                monthInList));
                            }
                            listData.add(new DataInListView(SocialSecurityAdapter.ITEM_TYPE_DIVIDER,"",""));
                            calculate=data.get(4).person;
                            if(calculate%100==0){
                                listData.add(
                                        new DataInListView(SocialSecurityAdapter.ITEM_TYPE_CONTENT_BOTTOM,
                                                "失业保险(个人)："+calculate/100,
                                                monthInList));
                            }else{
                                listData.add(
                                        new DataInListView(SocialSecurityAdapter.ITEM_TYPE_CONTENT_BOTTOM,
                                                "失业保险(个人)："+calculate/100.0f,
                                                monthInList));
                            }
                            pagerData.add(listData);
                        }
                    }
                    if(pagerData!=null&&pagerData.size()>0){
                        handleUi();
                    }else{
                        //无数据
                        initIntent();
                        mIntent.setClass(mContext,InquireNoDataActivity.class);
                        mIntent.putExtra(InquireNoDataActivity.TITLE_TEXT,"社保查询");
                        mIntent.putExtra(InquiriesActivity.CHANNEL_TYPE_S,
                                InquiriesActivity.CHANNEL_SHE_BAO);
                        startActivity(mIntent);
                        finish();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }
}
